﻿Imports Aricie.ComponentModel
Imports Aricie.DNN.Settings
Imports Aricie.DNN.Modules.LuceneSearch.Settings
Imports Aricie.DNN.Modules.LuceneSearch.Business
Imports LSCommon = Aricie.DNN.Modules.LuceneSearch.Common

Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports Aricie.Web.UI.Controls.GridViewGrouping
Imports Aricie.DNN.Modules.LuceneSearch.UI.Controls
Imports System.Linq

Namespace Aricie.DNN.Modules.LuceneSearch.UI

    Partial Public Class TemplateResultsControl
        Inherits LuceneResultsControlBase


#Region " Event Handlers"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                InitQuery()
                InitLayout()
            End If

            'Nécessaire au fonctionnement du pager lorsqu'ajax n'est pas activé.
            ' on affiche le pager si on est en mode printing mais que 
            Dim ShouldDisplayPagerWhenPrinting As Boolean = Not Me.Request.Params(LSCommon.Constants.UrlParameters.LuceneSearchModeParameter) = LSCommon.Constants.UrlParameters.PrintMode _
                                                            OrElse Not LuceneResultsSettings.DisablePagingForPrint

            If Me.phPager.Controls.Count = 0 AndAlso NbResults > 0 AndAlso ShouldDisplayPagerWhenPrinting Then
                AddPager(NbResults)
            End If
        End Sub



        Private Sub ddlCustomPageSize_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCustomPageSize.SelectedIndexChanged
            Dim strPageSize As String = Me.ddlCustomPageSize.SelectedValue
            Dim intPageSize As Integer
            If strPageSize = "Default" Then
                strPageSize = Me.LuceneResultsSettings.DefaultPageSize.ToString
            End If
            intPageSize = CInt(strPageSize)

            'Sauvegarder en cookie ou en base la nouvelle valeur
            If Me.UserId <> -1 Then
                UpdateUserNbResultsPerPage(intPageSize)
            Else
                UpdateCookiePageSize(intPageSize)
            End If

            'Faire un Bind
            PageSize = intPageSize
            PageIndex = 0
            OnRefreshData(New SearchParams(Me.LuceneFilterQuery, GetSortParameter, PageSize, PageIndex, True))

        End Sub



        Private Sub ctlGroupingField_SelectedItemChanged(ByVal sender As Object, _
                                                         ByVal e As ChangedEventArgs) _
                                                         Handles ctlGroupingField.SelectedItemChanged
            Try
                If ctlGroupingField.Visible Then
                    If e.NewValue IsNot Nothing Then
                        Grouping = DirectCast(e.NewValue, FieldDefinition).Id
                    Else
                        Grouping = ""
                    End If
                    OnRefreshData(New SearchParams(Me.LuceneFilterQuery, GetSortParameter, Me.PageSize, PageIndex, True))
                End If
            Catch ex As Exception
                ProcessModuleLoadException(Me, ex)
            End Try
        End Sub


        Private Sub ctlSortingField_SelectedItemChanged(ByVal sender As Object, _
                                                        ByVal e As ChangedEventArgs) _
                                                        Handles ctlSortingField.SelectedItemChanged
            Try

                If ctlSortingField.Visible Then
                    If e.NewValue IsNot Nothing Then
                        Sort = DirectCast(e.NewValue, FieldDefinition).Id
                    Else
                        Sort = ""
                    End If
                    OnRefreshData(New SearchParams(Me.LuceneFilterQuery, GetSortParameter, Me.PageSize, PageIndex, True))
                End If


            Catch ex As Exception
                ProcessModuleLoadException(Me, ex)
            End Try
        End Sub

        Protected Sub dgAllresults_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles dgAllresults.RowDataBound

            Try

                Select Case e.Row.RowType
                    Case DataControlRowType.Header
                        ' we do nothing in the header
                    Case DataControlRowType.DataRow

                        Dim result As LuceneSearchResultsInfo = DirectCast(e.Row.DataItem, LuceneSearchResultsInfo)
                        Dim ctlLiteral As Literal = DirectCast(e.Row.FindControl("ctlLuceneResult"), Literal)


                        Dim template As String = Me.GetItemTemplate(result, Global.Configuration.Templating.Context.TemplateTypes.Template.ToString(), Me.LuceneResultsSettings)
                        template = Me.TokenEngine.ReplaceSetTokens(template, result, "Result")
                        ctlLiteral.Text = HtmlDecode(template)

                End Select

            Catch ex As Exception
                ProcessModuleLoadException(Me, ex)
            End Try

        End Sub


#End Region


#Region "Functions"
        Private WithEvents _Helper As GridViewHelper
        Public Overrides Sub ConfigGrouping(ByVal fieldName As String)
            Dim groupControlField As DataControlField = DirectCast(Me.dgAllresults.Columns(0), DataControlField)

            Dim propertyField As String = fieldName
            
            If TypeOf groupControlField Is BoundField Then
                TryCast(groupControlField, BoundField).DataField = propertyField
            End If
            groupControlField.SortExpression = propertyField
            _Helper = New GridViewHelper(Me.dgAllresults, False, SortDirection.Ascending)
            _Helper.RegisterGroup(fieldName, True, False)

        End Sub




        Public Overrides Sub DisplayResults(ByVal resultsList As System.Collections.Generic.IList(Of Business.LuceneSearchResultsInfo), ByVal nbResultFound As Integer, ByVal sortFieldName As String, ByVal printMode As Boolean, Optional ByVal pageIndex As Integer = -1)
       
            dgAllresults.DataSource = resultsList
            If pageIndex <> -1 Then
                Me.PageIndex = pageIndex
            End If
            dgAllresults.PageIndex = Me.PageIndex
            dgAllresults.PagerSettings.Visible = False

            InitLayout()

            If Me.LuceneResultsSettings.DisablePagingForPrint AndAlso printMode Then
                Me.dgAllresults.AllowPaging = False
                Me.phPager.Visible = False
                Me.dgAllresults.DataBind()
            Else
                Me.dgAllresults.DataBind()
                AddPager(nbResultFound)
            End If
            NbResults = nbResultFound

        End Sub

        Public Sub InitLayout()
            ' on détermine la valeur du groupe
            tdGroupingfField.Visible = LuceneResultsSettings.AllowCustomGrouping
            If (Not IsPostBack AndAlso LuceneResultsSettings.AllowCustomGrouping) Then
                Dim GroupingName = EffectiveGrouping.ToLower()
                For i = 0 To ctlGroupingField.AllItems.Count - 1
                    If ctlGroupingField.AllItemsG(i).Id.ToLower = GroupingName Or Me.ctlGroupingField.AllItemsG(i).FriendlyName.ToLower = GroupingName Then
                        ctlGroupingField.DataBind()
                        ctlGroupingField.SelectedIndex = i + 1
                        Exit For
                    End If
                Next
            End If

            ' on détermine la valeur du tri
            tdSortingField.Visible = LuceneResultsSettings.AllowCustomSorting
            If (Not IsPostBack AndAlso LuceneResultsSettings.AllowCustomSorting) Then
                Dim SortingName = EffectiveSorting.ToLower()
                For i = 0 To ctlSortingField.AllItems.Count - 1
                    If ctlSortingField.AllItemsG(i).Id.ToLower = SortingName Or Me.ctlSortingField.AllItemsG(i).FriendlyName.ToLower = SortingName Then
                        ctlSortingField.DataBind()
                        ctlSortingField.SelectedIndex = i + 1
                        Exit For
                    End If
                Next
            End If

            tdCustomPageSize.Visible = LuceneResultsSettings.EnablePaging AndAlso LuceneResultsSettings.AllowCustomPageSize
            dgAllresults.AllowPaging = LuceneResultsSettings.EnablePaging OrElse LuceneResultsSettings.LimitResults
            dgAllresults.PagerSettings.Visible = LuceneResultsSettings.EnablePaging
            If dgAllresults.AllowPaging Then
                dgAllresults.PageSize = PageSize
            End If
            If tdCustomPageSize.Visible Then
                If PageSize <> -1 AndAlso ddlCustomPageSize.Items.FindByValue(PageSize.ToString()) IsNot Nothing Then
                    Try
                        ddlCustomPageSize.SelectedValue = PageSize.ToString()
                    Catch ex As Exception
                        Aricie.Services.ExceptionHelper.LogException(ex)
                    End Try
                Else
                    ddlCustomPageSize.SelectedValue = "Default"
                End If
            End If
        End Sub

        Public Overrides ReadOnly Property PagerHolder As System.Web.UI.WebControls.PlaceHolder
            Get
                Return phPager
            End Get
        End Property

#End Region
    End Class
End Namespace